import React, { useEffect, useRef, useState, forwardRef } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Flex, Input, Tag, theme, Tooltip } from 'antd';
const tagInputStyle = {
    width: 64,
    height: 22,
    marginInlineEnd: 8,
    verticalAlign: 'top',
};
export default forwardRef((props, ref) => {
    const { 
        value, 
        onChange, 
        placeholder = "添加标签", 
        maxLength = 20,
        disabled = false,
        ...restProps 
    } = props;
    const { token } = theme.useToken();
    const [tags, setTags] = useState([]);
    const [inputVisible, setInputVisible] = useState(false);
    const [inputValue, setInputValue] = useState('');
    const [editInputIndex, setEditInputIndex] = useState(-1);
    const [editInputValue, setEditInputValue] = useState('');
    const inputRef = useRef(null);
    const editInputRef = useRef(null);

    // 初始化tags从value
    useEffect(() => {
        if (value) {
            if (typeof value === 'string') {
                // 如果value是字符串，按逗号分割
                const tagArray = value.split(',').map(tag => tag.trim()).filter(tag => tag);
                setTags(tagArray);
            } else if (Array.isArray(value)) {
                // 如果value是数组，直接使用
                setTags(value);
            }
        } else {
            setTags([]);
        }
    }, [value]);

    // 当tags改变时，通知父组件
    const updateValue = (newTags) => {
        setTags(newTags);
        if (onChange) {
            // 返回逗号分隔的字符串，与原Input组件保持一致
            onChange(newTags.join(', '));
        }
    };

    useEffect(() => {
        if (inputVisible) inputRef.current?.focus();
    }, [inputVisible]);

    useEffect(() => {
        editInputRef.current?.focus();
    }, [editInputValue]);

    const handleClose = removedTag => {
        const newTags = tags.filter(tag => tag !== removedTag);
        updateValue(newTags);
    };
    const showInput = () => {
        if (!disabled) {
            setInputVisible(true);
        }
    };
    const handleInputChange = e => {
        setInputValue(e.target.value);
    };
    const handleInputConfirm = () => {
        if (inputValue && !tags.includes(inputValue)) {
            // 限制标签长度
            const trimmedValue = inputValue.length > maxLength ? inputValue.slice(0, maxLength) : inputValue;
            updateValue([...tags, trimmedValue]);
        }
        setInputVisible(false);
        setInputValue('');
    };
    const handleEditInputChange = e => {
        setEditInputValue(e.target.value);
    };
    const handleEditInputConfirm = () => {
        const newTags = [...tags];
        // 限制标签长度
        const trimmedValue = editInputValue.length > maxLength ? editInputValue.slice(0, maxLength) : editInputValue;
        newTags[editInputIndex] = trimmedValue;
        updateValue(newTags);
        setEditInputIndex(-1);
        setEditInputValue('');
    };
    const tagPlusStyle = {
        height: 22,
        background: token.colorBgContainer,
        borderStyle: 'dashed',
    };
    return (
        <Flex gap="4px 0" wrap>
            {tags.map((tag, index) => {
                if (editInputIndex === index) {
                    return (
                        <Input
                            ref={editInputRef}
                            key={tag}
                            size="small"
                            style={tagInputStyle}
                            value={editInputValue}
                            onChange={handleEditInputChange}
                            onBlur={handleEditInputConfirm}
                            onPressEnter={handleEditInputConfirm}
                        />
                    );
                }
                const isLongTag = tag.length > 20;
                const tagElem = (
                    <Tag
                        key={tag}
                        closable={!disabled}
                        style={{ userSelect: 'none' }}
                        onClose={() => handleClose(tag)}
                    >
                        <span
                            onDoubleClick={e => {
                                if (!disabled) {
                                    setEditInputIndex(index);
                                    setEditInputValue(tag);
                                    e.preventDefault();
                                }
                            }}
                        >
                            {isLongTag ? `${tag.slice(0, 20)}...` : tag}
                        </span>
                    </Tag>
                );
                return isLongTag ? (
                    <Tooltip title={tag} key={tag}>
                        {tagElem}
                    </Tooltip>
                ) : (
                    tagElem
                );
            })}
            {inputVisible ? (
                <Input
                    ref={inputRef}
                    type="text"
                    size="small"
                    style={tagInputStyle}
                    value={inputValue}
                    onChange={handleInputChange}
                    onBlur={handleInputConfirm}
                    onPressEnter={handleInputConfirm}
                />
            ) : (
                !disabled && (
                    <Tag style={tagPlusStyle} icon={<PlusOutlined />} onClick={showInput}>
                        {placeholder}
                    </Tag>
                )
            )}
        </Flex>
    );
});